package com.z.redis.command.impl.string;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisString;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import com.z.redis.resp.SimpleString;
import io.netty.channel.ChannelHandlerContext;

/**
 * SETNX key value
 * 当键不存在的时候设置键的值 如果键已经存在就不进行任何操作
 */
public class SetNx implements WriteCommand{
    private BytesWrapper key;
    private BytesWrapper value;

    @Override
    public CommandType type(){
        return CommandType.setnx;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        value = ((BulkString) array[2]).getContent();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        boolean exist = redisCore.exist(key);
        if(exist){
            ctx.writeAndFlush(new RespInt(0));
        }else{
            RedisString redisString = new RedisString(value);
            redisCore.put(key, redisString);
            ctx.writeAndFlush(new RespInt(1));
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        boolean exist = redisCore.exist(key);
        if(exist){
        }else{
            RedisString redisString = new RedisString(value);
            redisCore.put(key, redisString);
        }
    }
}
